package com.yunduansing.core.service.impl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.reflect.TypeToken;
import com.yunduansing.core.commons.DbCommon;
import com.yunduansing.core.commons.DbCommon.Grid;
import com.yunduansing.core.config.constant.SysConstant;
import com.yunduansing.core.dao.MenuDao;
import com.yunduansing.core.dao.redis.JedisClient;
import com.yunduansing.core.dto.MenuDetailDto;
import com.yunduansing.core.dto.MenuTree;
import com.yunduansing.core.dto.Template;
import com.yunduansing.core.model.ButtonModel;
import com.yunduansing.core.model.MenuModel;
import com.yunduansing.core.service.MenuService;
import com.yunduansing.core.utils.CommonUtil;
import com.yunduansing.core.utils.ResultUtil;

import net.spy.memcached.MemcachedClient;
import redis.clients.jedis.Jedis;

@Service
public class MenuServiceImpl implements MenuService {
	@Autowired
	private MenuDao dao;
	@Autowired
	private JedisClient jedisClient;

	public MenuModel getByKey(Object key) {
		return dao.getByKey(key);
	}

	public ResultUtil save(MenuModel entity) {
		try{
			if(entity.getId()>0)
				return ResultUtil.init(dao.update(entity)>0);
			else
				return ResultUtil.init(dao.add(entity)>0);
		}catch(Exception e){
			return ResultUtil.init(e);
		}
	}

	public ResultUtil deleteByKeys(List<Object> keys) {
		try{
			return ResultUtil.init(dao.deleteByKeys(keys)>0);
		}catch(Exception e){
			return ResultUtil.init(e);
		}
	}

	public Object pagination(Grid grid, Object search) {
		DbCommon.Pager pager=new DbCommon.Pager();
		pager.setIndex(grid.getIndex());
		pager.setData(dao.pagination(grid,search));
		pager.setRows(dao.pageCount(search));
		return pager;
	}

	public String getMenuJson(boolean showButton) {
		String res=null;
		List<MenuTree> treeList=new ArrayList<MenuTree>();
		List<MenuModel> list=null;
		//先从redis中查询是否已有，否则从数据库查询
		String menuCache=jedisClient.get(SysConstant.REDIS_SYS_MENU);
		if(menuCache==null){
			list= dao.getAll();
			jedisClient.set(SysConstant.REDIS_SYS_MENU,CommonUtil.toJsonWithGson(list));
			jedisClient.expire(SysConstant.REDIS_SYS_MENU, SysConstant.REDIS_SYS_MENU_EXPIRE);
		}
		else
			list=CommonUtil.fromJson(menuCache);
		for(MenuModel item:list){
			if(item.getParent_id()==0){
				MenuTree t=new MenuTree();
				t.setChecked(false);
				t.setName(item.getName());
				t.setId(item.getId());
				treeList.add(t);
			}
		}
		treeList=getMenuZTree(0,list,showButton?getButtonAll():null);
		res=CommonUtil.toJsonWithGson(treeList);
		return res;
	}
	
	private List<MenuTree> getMenuZTree(int pid,List<MenuModel> list,List<ButtonModel> buttons){
		List<MenuTree> menu=new ArrayList<MenuTree>();
		for(MenuModel item:list){
			if(item.getParent_id()==pid){
				MenuTree t=new MenuTree();
				t.setChecked(false);
				t.setName(item.getName());
				t.setId(item.getId());
				t.setUrl(item.getUrl());
				menu.add(t);
			}
		}
		for(MenuTree item:menu){
			if(item!=null&&item.getUrl()!=null&&item.getUrl().isEmpty()){
				System.out.println("空");
				item.setChildren(getMenuZTree(item.getId(),list,buttons));
			}
			if(buttons!=null&&item!=null&&item.getUrl()!=null&&!item.getUrl().isEmpty()){
				List<MenuTree> btnChildren=new ArrayList<MenuTree>();
				for(ButtonModel btn:buttons){
					if(btn.getMenu_id()==item.getId()){
						MenuTree treeItem=new MenuTree();
						treeItem.setChecked(false);
						treeItem.setId(btn.getId());
						treeItem.setName(btn.getName()+"（按钮）");
						btnChildren.add(treeItem);
					}
				}
				if(btnChildren.size()>0)
					item.setChildren(btnChildren);
			}
		}
		if(menu.size()==0)
			return null;
		return menu;
	}

	private void jedisTest(){
		Jedis jedis=new Jedis("localhost");
		System.out.println("Connection to server sucessfully");
	    jedis.set("redisKey", "Java redis String test");
	    System.out.println("Redis key is:"+jedis.get("redisKey"));
	    
	    jedis.lpush("redis-list", "Redis");
	    jedis.lpush("redis-list", "mysql");
	    jedis.lpush("redis-list", "mongodb");
	    
	    List<String> list=jedis.lrange("redis-list", 0, 5);
	    for(String item:list){
	    	System.out.println("Redis list:"+item);
	    }
	    
	    Set<String> keys=jedis.keys("*");
	    Iterator<String> it=keys.iterator();
	    while(it.hasNext())
	    	System.out.println("Redis keys list is:"+it.next());
	}

	public MenuDetailDto getModelAndParentById(int id) {
		return dao.getModelAndParentById(id);
	}

	public Object getButtonsByMenuId(int menuId) {
		return dao.getButtonsByMenuId(menuId);
	}

	public ResultUtil saveButton(ButtonModel model) {
		try{
			if(model.getId()>0)
				return ResultUtil.init(dao.updateButton(model)>0);
			else
				return ResultUtil.init(dao.addButton(model)>0);
		}catch(Exception ex){
			return ResultUtil.init(ex);
		}
	}

	public ResultUtil deleteButtonById(int id) {
		try{
			return ResultUtil.init(dao.deleteButtonById(id)>0);
		}catch(Exception e){
			return ResultUtil.init(e);
		}
	}

	public List<ButtonModel> getButtonAll() {
		String btnCache=jedisClient.get(SysConstant.REDIS_SYS_BUTTON);
		List<ButtonModel> btnList=null;
		//先从redis中看是否存在，否则从数据库中取
		if(btnCache==null){
			btnList=dao.getButtonAll();
			jedisClient.set(SysConstant.REDIS_SYS_BUTTON,CommonUtil.toJsonWithGson(btnList));
			jedisClient.expire(SysConstant.REDIS_SYS_BUTTON, SysConstant.REDIS_SYS_BUTTON_EXPIRE);
		}else
			btnList=CommonUtil.fromJson(btnCache);
		return btnList;
	}
}
